{
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
}

unit ExeTestUtils;

interface

uses
  Classes, SysUtils, MiscUtils, zstreamCustom, CrcUtils, TestUtils;

procedure ExtractItStreamFromExe(const ExeFileName: String; Target: TStream;
  out TestTitle: String);

implementation

resourcestring
  SExtractError = 'Can''t extract the test.';

procedure ExtractItStreamFromExe(const ExeFileName: String; Target: TStream;
  out TestTitle: String);
const
  FOOTER_SIZE = SizeOf(Int64) + SizeOf(Cardinal);
var
  ExeStream: TUnicodeFileStream;
  Crc32: Cardinal;
  TestSize: Int64;
  DecompressionStream: TDecompressionStream;
begin
  ExeStream := TUnicodeFileStream.OpenForRead(ExeFileName);
  try
    if ExeStream.Size < FOOTER_SIZE then
      raise Exception.Create(SExtractError);

    Crc32 := ComputeStreamChunkCrc32(ExeStream, ExeStream.Size - SizeOf(Cardinal));
    if ReadStreamCardinal(ExeStream) <> Crc32 then
      raise Exception.Create(SExtractError);

    ExeStream.Seek(-FOOTER_SIZE, soFromEnd);
    TestSize := ReadStreamInt64(ExeStream);

    ExeStream.Seek(-FOOTER_SIZE - TestSize, soFromEnd);
    if ReadStreamFixedString(ExeStream, Length(TEST_DOCUMENT_MIME_TYPE)) <> TEST_DOCUMENT_MIME_TYPE then
      raise Exception.Create(SExtractError);

    TestTitle := ReadStreamSizedString(ExeStream);

    DecompressionStream := TDecompressionStream.Create(ExeStream, TRUE);
    try
      Target.CopyFrom(DecompressionStream, 0);
    finally
      DecompressionStream.Free;
    end;
  finally
    ExeStream.Free;
  end;
end;

end.

